package swu.client;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import swu.core.ServletController;
import swu.user.User;
import swu.user.UserRepo;
import swu.user.UserService;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet(urlPatterns = "/register")
public class ClientRegisterServlet extends ServletController
{
    private final UserRepo userRepo = new UserRepo();
    private final UserService userService = new UserService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        String userName = req.getParameter("userName");
        String password = req.getParameter("password");

        User user = new User(userName,password);

        try
        {
            if(this.userRepo.isUserExists(user))
            {
                resp.setContentType("text/html;charset=UTF-8");
                resp.getWriter().println("<script>alert('该用户已存在');</script>");
                resp.setHeader("Refresh", "1; URL=./index.html");
            }
            else
            {
                this.userRepo.addUser(user);
                resp.setContentType("text/html;charset=UTF-8");
                resp.getWriter().println("<script>alert('注册成功');</script>");
                resp.setHeader("Refresh", "1; URL=./index.html");
            }
        } catch (SQLException e)
        {
            throw new RuntimeException(e);
        }
    }
}
